package com.xwaf.platform.system.auth.serviceimpl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xwaf.platform.common.api.constants.RedisKeys;
import com.xwaf.platform.common.api.entity.ELUser;
import com.xwaf.platform.common.redis.util.RedisUtil;
import com.xwaf.platform.common.service.service.CrudService;
import com.xwaf.platform.common.utils.StringHelper;
import com.xwaf.platform.system.api.entity.DataBase;
import com.xwaf.platform.system.api.entity.auth.User;
import com.xwaf.platform.system.api.entity.auth.UserPermission;
import com.xwaf.platform.system.api.enums.UserPermissionType;
import com.xwaf.platform.system.api.enums.UserStatus;
import com.xwaf.platform.system.api.request.auth.DistributionTemplateRequest;
import com.xwaf.platform.system.api.service.auth.UserPermissionService;
import com.xwaf.platform.system.api.service.auth.UserService;
import com.xwaf.platform.system.auth.dao.UserPermissionDao;

/**
 * 
 * <p>
 * 用户权限表
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2019-5-25 12:21:24 <br>
 * @see 无<br>
 *      Copyright (c) 2019, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@Transactional(readOnly = true)
@Service("userPermissionService")
public class UserPermissionServiceImpl extends CrudService<UserPermissionDao, UserPermission>
		implements UserPermissionService {

	@Autowired
	private UserPermissionDao userPermissionDao;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserService userService;

	@Override
	public Page<UserPermission> selPageList(Page<UserPermission> page, UserPermission userPermission) {
		List<UserPermission> list = userPermissionDao.selPageList(page, userPermission);
		page.setRecords(list);
		return page;
	}

	@Override
	public List<String> findUserAllPermissionCodes(String userId) {
		return userPermissionDao.findUserAllPermissionCodes(userId);
	}

	@Override
	@Transactional(readOnly = false, isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public boolean distributionTemplate(DistributionTemplateRequest distributionTemplateRequest, ELUser user) {
		boolean flag = true;
		String modules[] = distributionTemplateRequest.getCheckModules();
		String operations[] = distributionTemplateRequest.getCheckOperations();
		String fields[] = distributionTemplateRequest.getCheckFields();
		if (StringHelper.isEmpty(distributionTemplateRequest.getUid())) {
			flag = false;
		} else {
			// 先删除用户拥有的权限
			Wrapper<UserPermission> wrapper = new EntityWrapper<UserPermission>();
			wrapper.where("user_id={0}", distributionTemplateRequest.getUid());
			userPermissionDao.delete(wrapper);
			// 判断是否选择了模块权限
			if (modules != null && modules.length > 0) {
				for (String module : modules) {
					if (!StringHelper.isEmpty(module)) {
						saveUserPermisson(distributionTemplateRequest.getUid(), module, UserPermissionType.MODULE,
								user);
					}
				}
			}
			// 判断是否选择了操作权限
			if (operations != null && operations.length > 0) {
				for (String operation : operations) {
					if (!StringHelper.isEmpty(operation)) {
						saveUserPermisson(distributionTemplateRequest.getUid(), operation, UserPermissionType.OPERATION,
								user);
					}
				}
			}
			// 判断是否选择了敏感字段权限
			if (fields != null && fields.length > 0) {
				for (String field : fields) {
					if (!StringHelper.isEmpty(field)) {
						saveUserPermisson(distributionTemplateRequest.getUid(), field, UserPermissionType.FIELD, user);
					}
				}
			}
			redisUtil.remove(RedisKeys.PERMISSION_MODULE);
		}
		// 判断分配用户状态，如果为待分配则修改为激活
		User grantUser = userService.selectById(distributionTemplateRequest.getUid());
		if (grantUser.getStatus().equals(UserStatus.UNGRANT)) {
			User u = new User();
			u.setStatus(UserStatus.ACTIVED);
			u.setUpdateBy(user.getId());
			u.setUpdateTime(new Date());
			userService.updateById(grantUser);
		}
		return flag;
	}

	/**
	 * 
	 * <p>
	 * 保存用户权限
	 * <p>
	 * 
	 * @author 李聪 <br>
	 * @email xwaf_love@yeah.net <br>
	 * @since JDK 1.8<br>
	 * @date 2020年1月3日 下午4:29:52 <br>
	 * @see 无<br>
	 * @param uid
	 * @param permissionCode
	 * @param userPermissionType
	 * @param user
	 * @demo <br>
	 */
	private void saveUserPermisson(String uid, String permissionCode, UserPermissionType userPermissionType,
			ELUser user) {
		UserPermission m = new UserPermission();
		m.setId(DataBase.getDataBaseId(DataBase.UP));
		m.setPermissionCode(permissionCode);
		m.setUserId(uid);
		m.setPermissionType(userPermissionType);
		m.setCreateBy(user.getId());
		m.setCreateTime(new Date());
		m.setUpdateTime(new Date());
		userPermissionDao.insert(m);
	}

}
